package com.authine.cloudpivot.ext.service.ipml;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.facade.UserFacade;
import com.authine.cloudpivot.engine.api.model.dto.SimpleMsgDTO;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.enums.type.IMMessageChannelType;
import com.authine.cloudpivot.engine.enums.type.IMMessageType;
import com.authine.cloudpivot.engine.service.impl.component.RuntimeMessageComponent;
import com.authine.cloudpivot.engine.service.message.IMessageService;
import com.authine.cloudpivot.ext.service.BlowWhistleEventService;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import com.authine.cloudpivot.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class BlowWhistleEvent2ServiceIpml implements BlowWhistleEventService {



    private String workCode ="internal_processes_v1";


    @Autowired
    private JPANativeQuery jpaNativeQuery;
    @Autowired
    private UserFacade userFacade;

    @Autowired
    private RedisTemplate redisTemplate;


    private BlowWhistleEvent2ServiceIpml(){}


    @Override
    public void pushTimedOutToDo() {


        String title="超时提醒";
        String cont="您的【%s】已经超时，请及时处理！";

        Date nowTime = new Date(); //先取当前时间
        String querySql = String.format("SELECT\n" +
                        "\tv.id,\n" +
                        "\tv.event_theme,\n" +
                        "\tv.event_type,\n" +
                        "\tv.event_type_v2,\n" +
                        "\tv.event_type_v3,\n" +
                        "\tbim.instanceName,\n" +
                        "\tbim.participant,\n" +
                        "\tbim.instanceId,\n" +
                        "\tbim.activityCode,\n" +
                        "\tbim.startTime\n" +
                        "FROM\n" +
                        "\tbiz_workitem bim\n" +
                        "\tLEFT JOIN ikhmj_internal_processes_v1 v ON bim.instanceId = v.workflowInstanceId \n" +
                        "WHERE\n" +
                        "\tbim.workflowCode = '%s' and v.sequenceStatus = 'PROCESSING'"
                ,workCode);


        List list =null;
        try {

             list = jpaNativeQuery.getList(querySql, null, null);
        } catch (Exception e) {
            log.info("超时提醒查询SQL:",querySql);
            log.error("查询异常：",e);
        }
        if (CollectionUtils.isEmpty(list)){
            log.info("超时提醒无数据需要推送");
            return;
        }
        //创建推送服务
        IMessageService messageService = RuntimeMessageComponent.getMessageService(IMMessageChannelType.DINGTALK.name());
        for (Object res : list) {
            HashMap map = (HashMap) res;
            String eventTheme = MapUtils.getString(map, "event_theme");
            String eventType = MapUtils.getString(map, "event_type");
            String eventTypeV2 = MapUtils.getString(map, "event_type_v2");
            String eventTypeV3 = MapUtils.getString(map, "event_type_v3");
            String queryTimeSql = String.format("SELECT blsx FROM `ilrv7_wlfljcxx` where blsx is not null and sjzt = '%s' and yjfl = '%s' and ejfl='%s' and sjfl='%s' limit 1",eventTheme,eventType,eventTypeV2,eventTypeV3);
            if (StringUtils.isBlank(eventTypeV3)){
                queryTimeSql = String.format("SELECT blsx FROM `ilrv7_wlfljcxx` where blsx is not null and sjzt = '%s' and yjfl = '%s' and ejfl='%s' and sjfl is null limit 1",eventTheme,eventType,eventTypeV2,eventTypeV3);
            }
            List<Map<String,BigDecimal>> list1 = jpaNativeQuery.getList(queryTimeSql, null, null);
            if (CollectionUtils.isEmpty(list1)||list1.get(0)==null){
                continue;
            }
            Map<String, BigDecimal> stringBigDecimalMap = list1.get(0);
            BigDecimal bigDecimal = stringBigDecimalMap.get("blsx");
            int days = bigDecimal.intValue();
            String time = StringUtil.dateTransition(MapUtils.getString(map, "startTime"),"yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startTime = null;
            try {
                startTime = simpleDateFormat.parse(time);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            long between = DateUtil.between(startTime, nowTime, DateUnit.DAY);
            if (between>days){
                String instanceName = MapUtils.getString(map, "instanceName");
                String participant = MapUtils.getString(map, "participant");
                cont = String.format(cont,instanceName);
                UserModel user = userFacade.get(participant);
                String id = MapUtils.getString(map, "id");
                String key = id+"_"+participant;
                if (redisTemplate.hasKey(key)){
                    continue;
                }
                this.senDingTalkMessage(messageService,user,title,cont);
                redisTemplate.opsForValue().set(key,null, days, TimeUnit.DAYS);
                log.info("【待办超时推送消息】：用户:{}，标题：{}，内容：{}",user.getName() ,title, cont);
            }
        }

    }



    /**
     * 验证当前时间是否需要进行推送
     * @return  true=不推送  false = 提送
     * */
    private  boolean virifyPush(){
        int hour = LocalDateTime.now().getHour();

        List list = jpaNativeQuery.getList("select * from push_hour ", null, null);
        HashMap hashMap = (HashMap) list.get(0);
        Integer start = MapUtils.getInteger(hashMap, "start", 0);
        Integer end = MapUtils.getInteger(hashMap, "end", 24);


        if (start <= hour && end >= hour ){
            return false;
        }

        log.warn("当前时间段为：{}时，不进行推送",hour);
        return true;
    }


    /**
     * 验证当前时间是否需要进行推送
     * @return  true=推送  false = 不提送
     * */
    private  boolean virifyPush(LocalDateTime localDateTime,LocalDateTime startTime,Integer integer){

        Duration duration = Duration.between(startTime, localDateTime);
        long minutes = duration.toMinutes();

        long pus = minutes % 60;
        //只有pus 值 在 0 和 10 之间可以推送
        if(integer >pus && 0 <= pus && 10 >= pus){
            return true;
        }

        log.debug("当前时间不在推送时间范围不进行推送， 实际相差：{}分钟",pus);
        return false;
    }



    private void senDingTalkMessage(IMessageService messageService, UserModel user , String title, String content){

        if (StringUtils.isEmpty(user.getUserId())){
            log.warn("用户钉钉ID为空，不推送钉钉消息！");
            return;
        }

        SimpleMsgDTO dto = new SimpleMsgDTO();
        try {

            //钉钉userId
            dto.setReceivers(user.getUserId());
            dto.setContent(content);
            dto.setTitle(title);
            dto.setMessageType(IMMessageType.BUSINESS_REMIND);
            dto.setCorpId(user.getCorpId());
            messageService.sendSimpleTextMsg(dto);
        } catch (Exception e) {
            log.info("用户：{}-账号：{}，送消息内容：{}",user.getName(),user.getUsername(),JSONObject.toJSONString(dto));
            log.error("钉钉消息发送失败",e);
        }
    }

}
